﻿using Prism.Commands;
using Prism.Mvvm;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Data;
using Microsoft.Win32;
using System.ComponentModel;
using System.Threading.Tasks;
using System;
using Prism.Regions;
using System.Diagnostics;
using System.Windows.Input;
using FullApp1.Services;
using Prism.Services.Dialogs;
using FullApp1.Modules.ModuleName.Models;
using System.Windows.Media.Imaging;
using System.Globalization;

namespace FullApp1.Modules.ModuleName.ViewModels
{
    public class LicenseDetailViewModel : BindableBase, INavigationAware
    {        
        private readonly IExportService _exportService;
        private readonly IDialogService _dialogService;
        private LicenseInfo _selectedLicense;

        //private readonly INavigationService _navigationService;
        private readonly IRegionManager _regionManager;
        

        public DelegateCommand ReturnToList => new DelegateCommand(ExecuteReturnToList);
        public LicenseInfo SelectedLicense
        {
            get => _selectedLicense;
            set => SetProperty(ref _selectedLicense, value);
        }
        private LegalPerson _legalPerson;
        public LegalPerson LegalPerson 
        { 
            get => _legalPerson; 
            set => SetProperty(ref _legalPerson, value); }
        public BitmapImage IDCardFront { get; set; }
        public BitmapImage IDCardBack { get; set; }       

        // 学历选项集合
        public ObservableCollection<EducationLevel> EducationLevels { get; }
            = new ObservableCollection<EducationLevel>(EducationLevel.DefaultLevels);

        // 当前选中的学历
        private EducationLevel _selectedEducation;
        public EducationLevel SelectedEducation
        {
            get => _selectedEducation;
            set => SetProperty(ref _selectedEducation, value);
        }

        public void UpdateLegalPersonInfo(BaiduOCRResult result, bool isBackSide = false)
        {
            if (result == null) return;

            // 保留已有数据（如果已存在）
            if (LegalPerson == null)
            {
                LegalPerson = new LegalPerson();
            }

            // 仅当处理正面时更新基础信息
            if (!isBackSide)
            {
                LegalPerson.Name = result.Name;
                LegalPerson.Ethnicity = result.Ethnic;
                LegalPerson.IDNumber = result.IdNumber;
                LegalPerson.Address = result.Address;
            }

            // 处理有效期（背面专用）
            if (!string.IsNullOrEmpty(result.ValidDateStart))
            {
                try
                {
                    LegalPerson.ValidDateStart = DateTime.ParseExact(
                        result.ValidDateStart,
                        "yyyyMMdd",
                        CultureInfo.InvariantCulture
                    );
                    LegalPerson.ValidDateEnd = DateTime.ParseExact(
                        result.ValidDateEnd,
                        "yyyyMMdd",
                        CultureInfo.InvariantCulture
                    );
                    //LegalPerson.ValidityYears = LegalPerson.ValidDateEnd.Year - LegalPerson.ValidDateStart.Year;
                }
                catch (FormatException)
                {
                    // 错误处理：记录日志或显示提示
                    Debug.WriteLine("日期格式解析失败");                    
                }
            }

            // 触发属性变更通知
            RaisePropertyChanged(nameof(LegalPerson));
        }

        // 打开经营者详情对话框
        public DelegateCommand ShowOperatorDetailCommand => new DelegateCommand(() =>
        {
            if (SelectedLicense?.legalPerson == null) return;

            var parameters = new DialogParameters
        {
            { "operator", SelectedLicense.legalPerson }
        };

            _dialogService.ShowDialog("OperatorDetailDialog", parameters, result =>
            {
                if (result.Result == ButtonResult.OK)
                {
                    // 处理对话框返回结果（例如更新经营者信息）
                    var updatedOperator = result.Parameters.GetValue<LegalPerson>("operator");
                    SelectedLicense.legalPerson = updatedOperator;
                }
            });
        });

        public LicenseDetailViewModel(IExportService exportService, 
            IRegionManager regionManager,
            IDialogService dialogService)
        {
            _exportService = exportService;
            _regionManager = regionManager ?? throw new ArgumentNullException(nameof(regionManager));
            _dialogService = dialogService;

            // 测试数据初始化（根据实际需求替换为真实数据）
            SelectedLicense = new LicenseInfo
            {
                legalPerson = new LegalPerson
                {
                    Name = "张三",
                    Ethnicity = "汉族",
                    IDNumber = "110101199003077654",
                    Address = "北京市朝阳区",
                    ValidDateStart = new DateTime(2010, 1, 1),
                    ValidDateEnd = new DateTime(2030, 1, 1),
                    Phone = "13800138000",
                    Wechat = "zhangsan123",
                    Education = "本科"
                }
            };
        }

        private void ExecuteReturnToList()
        {
            // 返回上一页
            _regionManager.RequestNavigate("ContentRegion", "ExistingPage");
        }

        public void OnNavigatedTo(NavigationContext parameters)
        {            
            if (parameters.Parameters.TryGetValue<LicenseInfo>("selectedLicense", out var license))
            {
                SelectedLicense = license;
            }
        }

        public bool IsNavigationTarget(NavigationContext parameters) => false;
        public void OnNavigatedFrom(NavigationContext parameters) { }
    }
}